package com.bigtotoro.shuiyincamera;

import android.app.ProgressDialog;
import android.content.Intent;
import android.media.MediaPlayer;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.DragEvent;
import android.view.View;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.view.animation.LinearInterpolator;
import android.widget.ImageView;
import android.widget.SeekBar;
import android.widget.TabHost;
import android.widget.TextView;
import android.widget.Toast;

import com.bigtotoro.shuiyincamera.editimage.utils.FileUtil;
import com.bigtotoro.shuiyincamera.image.RemoveWaterMarkActivity;
import com.bigtotoro.shuiyincamera.model.MyArt;
import com.bigtotoro.shuiyincamera.util.AudioItem;
import com.bigtotoro.shuiyincamera.util.MyUtils;
import com.bigtotoro.shuiyincamera.util.VideoUtil;
import com.bigtotoro.shuiyincamera.video.VideoAddWater2Activity;
import com.bigtotoro.shuiyincamera.video.VideoConcatActivity;
import com.bigtotoro.shuiyincamera.video.view.MusicCropView;
import com.umeng.analytics.MobclickAgent;

import java.io.IOException;

import io.microshow.rxffmpeg.RxFFmpegInvoke;
import io.microshow.rxffmpeg.RxFFmpegSubscriber;
import qiu.niorgai.StatusBarCompat;

import static com.bigtotoro.shuiyincamera.editimage.Constacts.EXTRA_OUTPUT;

//视频剪裁，截取视频中某一部分图像，生成新视频

public class MusicCropActivity extends BaseActivity implements View.OnClickListener {
    public static final String TAG = "music-crop";
    public static final int SEEK_CLOSEST = 0x03;

    private ImageView iv_photo;
    private TextView tv_name, crop_time_info;
    private SeekBar seekBar;
    private ImageView btn_reset, btn_play;//重置和播放按钮

    private String path;
    private int duration = 0;
    private MediaPlayer mMediaPlayer;

    private MusicCropView musicCropView;
    private boolean pause = false;



    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_music_crop);
        StatusBarCompat.setStatusBarColor(this, getResources().getColor(R.color.theme_color));
        //添加友盟事件统计
        MyUtils.addUmengEvent(MusicCropActivity.this,"music_crop","音频分割");
        initBase();
        initView();
    }

    private int isNew = -1;
    private void initView() {
        musicCropView = findViewById(R.id.music_crop);
        iv_photo = findViewById(R.id.iv_photo);
        tv_name = findViewById(R.id.tv_name);
        crop_time_info = findViewById(R.id.crop_time_info);
        seekBar = findViewById(R.id.opacitySeekBar);
        btn_reset = findViewById(R.id.btn_reset);
        btn_play = findViewById(R.id.btn_play);

        findViewById(R.id.btn_save).setOnClickListener(this);

        path = getIntent().getStringExtra("path"); //音乐地址
        isNew = getIntent().getIntExtra("isNew",-1);
        //加载音乐
        initMediaPlayer();
        seekBar.setMax(mMediaPlayer.getDuration());
        Handler handler = new Handler();
        Runnable updateThread = new Runnable() {
            @Override
            public void run() {
                if (!pause && mMediaPlayer != null) {
                    seekBar.setProgress(mMediaPlayer.getCurrentPosition());
                    handler.postDelayed(this, 100); //每0.1秒更新一次进度

                    if(duration>0&&mMediaPlayer.getCurrentPosition()>musicCropView.getRightTime()){
                        mMediaPlayer.seekTo(musicCropView.getLeftTime());
                    }
                }
            }
        };
        new Thread(updateThread).start();
        seekBar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
            @Override
            public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
            }

            @Override
            public void onStartTrackingTouch(SeekBar seekBar) {
                handler.removeCallbacks(updateThread);
            }

            @Override
            public void onStopTrackingTouch(SeekBar seekBar) {
                mMediaPlayer.seekTo(seekBar.getProgress());
                handler.postDelayed(updateThread, 1000);
            }
        });
        btn_play.setOnClickListener(this);
        btn_reset.setOnClickListener(this);
    }


    //计算播放时间
    public String calculateTime(int time) {
        int minute;
        int second;
        if (time > 60) {
            minute = time / 60;
            second = time % 60;
            //分钟再0~9
            if (minute >= 0 && minute < 10) {
                //判断秒
                if (second >= 0 && second < 10) {
                    return "0" + minute + ":" + "0" + second;
                } else {
                    return "0" + minute + ":" + second;
                }
            } else {
                //分钟大于10再判断秒
                if (second >= 0 && second < 10) {
                    return minute + ":" + "0" + second;
                } else {
                    return minute + ":" + second;
                }
            }
        } else if (time < 60) {
            second = time;
            if (second >= 0 && second < 10) {
                return "00:" + "0" + second;
            } else {
                return "00:" + second;
            }
        }
        return null;
    }

    /*
     * 初始化MediaPlayer
     * */
    private void initMediaPlayer() {
        mMediaPlayer = new MediaPlayer();
        try {

            mMediaPlayer.setDataSource(MusicCropActivity.this, Uri.parse(path)); //加载音乐
            mMediaPlayer.prepare();
            mMediaPlayer.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
                @Override
                public void onPrepared(MediaPlayer mp) {

                    mMediaPlayer.start();
                    mMediaPlayer.setLooping(true);//循环播放

                    playCDAni();
                    //播放按钮改变
                    btn_play.setImageResource(R.mipmap.btn_stop);
                    duration = mp.getDuration();
                    musicCropView.setOnMusicDragListener(new MusicCropView.OnMusicDragListener() {
                        @Override
                        public void onDrag(int type, int left, int right) {
                            if(type==0){//左边拖拽，每次重新左边开始播放
//                                seekBar.setProgress(left*100/duration);
                                mMediaPlayer.seekTo(left);
                            }
                            if(type==1){
                                if(mMediaPlayer.getCurrentPosition()>=right){
                                    mMediaPlayer.seekTo(left);
                                }
                            }

                            crop_time_info.setText("已截取"+String.format("%.1f", (musicCropView.getRightTime()-musicCropView.getLeftTime())*1.0/1000)+"s");
                        }
                    });
                    musicCropView.setDuration(duration);
                    crop_time_info.setText("已截取"+String.format("%.1f", (duration)*1.0/1000)+"s");
                }
            });
        } catch (Exception e) {
            e.printStackTrace();
        }
        int duration2 = mMediaPlayer.getDuration() / 1000;
        int position = mMediaPlayer.getCurrentPosition();
//        tv_duration_left.setText(calculateTime(position / 1000)); //开始进度
//        tv_duration_right.setText(calculateTime(duration2)); //结束进度

    }

    private ProgressDialog mProgressDialog;
    private String out;//裁剪后的保存路径

    private void save() {
        //添加水印后视频保存地址
        out = VideoUtil.VIDEO_OUT_DIR + "/" + System.currentTimeMillis() + ".mp3";
        mProgressDialog = new ProgressDialog(this);
        mProgressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
        mProgressDialog.setMax(100);
        mProgressDialog.setCancelable(false);
        mProgressDialog.setCanceledOnTouchOutside(false);
        mProgressDialog.setTitle("正在处理");
        mProgressDialog.show();


        //音频裁剪
        //-ss : 指定从那裡开始
        //-t : 指定到那裡结束
        //-acodec copy : 编码格式和来源档桉相同（就是mp3）
        //ffmpeg -i your_audio_file.mp3 -acodec copy -t 00:30:00 -ss 00:00:00 half_hour_split.mp3
        String cmd = String.format("ffmpeg -y -ss %s -t %s -i %s %s",String.format("%.1f",musicCropView.getLeftTime()*1.0f/1000), String.format("%.1f", (musicCropView.getRightTime()-musicCropView.getLeftTime())*1.0f/1000), path, out);
        Log.d(TAG, "cmd "+cmd);
        String[] commands = cmd.split(" ");
        try {
            RxFFmpegInvoke.getInstance().runCommandRxJava(commands).subscribe(new RxFFmpegSubscriber() {
                @Override
                public void onFinish() {
                    Log.i(TAG, "EpEditor.execCmd onSuccess");
                    mHandler.sendEmptyMessage(MSG_SUCCESS);
                }

                @Override
                public void onProgress(int progress, long progressTime) {
                    Log.i(TAG, "EpEditor.execCmd onProgress");
                    Message msg = new Message();
                    Bundle data = new Bundle();
                    data.putFloat("progress", progress);
                    msg.setData(data);
                    msg.what = MSG_PROGRESS;
                    mHandler.sendMessage(msg);

                }

                @Override
                public void onCancel() {
                    Log.i(TAG, "EpEditor.execCmd onFailure");
                    mHandler.sendEmptyMessage(MSG_CANCLE);
                }

                @Override
                public void onError(String message) {
                    Log.i(TAG, "error "+message);
                    mHandler.sendEmptyMessage(MSG_FAIL);
                }
            });

        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public static final int MSG_SUCCESS = 101;
    public static final int MSG_FAIL = 102;
    public static final int MSG_PROGRESS = 103;
    public static final int MSG_CANCLE = 104;
    private Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            if (msg.what == MSG_SUCCESS) {
                Log.i("视频去水印", "去水印完成，跳转");
                Toast.makeText(MusicCropActivity.this, "处理完成", Toast.LENGTH_SHORT).show();
                MyArt art = new MyArt();
                art.setHeight(0);
                art.setWidth(0);
                art.setCreate_time(System.currentTimeMillis() + "");
                art.setPath(out);
                art.setType(2);
                art.save();
                if (mProgressDialog.isShowing()) {
                    mProgressDialog.dismiss();
                }
//                if (isNew > 0){ //文件名包含中文，使用的复制文件操作
//                    MyUtils.DeleteFolder(path); //处理完成后，删除缓存文件
//                }

//                FileUtil.ablumUpdate(MusicCropActivity.this, art.getPath(),2);//更新相册
                Intent intent = new Intent(MusicCropActivity.this, ShowMyArtsActivity.class);
                intent.putExtra(EXTRA_OUTPUT, out);
                intent.putExtra("create_time", art.getTrueCreateTime());
                intent.putExtra("width", 0);
                intent.putExtra("height", 0);
                intent.putExtra("type", "2");
                startActivity(intent);
                finish();

            } else if (msg.what == MSG_FAIL) {
                Toast.makeText(MusicCropActivity.this, "处理失败", Toast.LENGTH_SHORT).show();
                if (mProgressDialog.isShowing()) {
                    mProgressDialog.dismiss();
                }
            } else if (msg.what == MSG_PROGRESS) {
                float progress = msg.getData().getFloat("progress");
                mProgressDialog.setProgress((int) (progress));
            } else if (msg.what == MSG_CANCLE) {
                float progress = msg.getData().getFloat("progress");
                mProgressDialog.setProgress((int) (progress));
            }
        }
    };


    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.btn_reset:
                if(duration>0){
                    mMediaPlayer.seekTo(musicCropView.getLeftTime());
                    btn_play.setImageResource(R.mipmap.btn_stop);
                }
                break;
            case R.id.btn_save: //保存裁剪后的音频

                //添加友盟事件统计
                MyUtils.addUmengEvent(MusicCropActivity.this,"music_crop_save","音频分割保存");

                save();
                break;
            case R.id.btn_play:
                if (mMediaPlayer.isPlaying()) {
                    mMediaPlayer.pause();
                    btn_play.setImageResource(R.mipmap.btn_play);
                    stopCDAni();

                } else {
                    mMediaPlayer.start();
                    btn_play.setImageResource(R.mipmap.btn_stop);
                    playCDAni();
                }
                break;
        }
    }

    private Animation animation;
    private void playCDAni(){
        if(iv_photo.getAnimation()==null){
            if (animation == null){
                animation = AnimationUtils.loadAnimation(this, R.anim.music_cd);
                LinearInterpolator lin = new LinearInterpolator();
                animation.setInterpolator(lin);
            }

            iv_photo.startAnimation(animation);
        }
    }

    private void stopCDAni(){
        if(iv_photo.getAnimation()!=null){
            iv_photo.clearAnimation();
        }
    }

    @Override
    public void onResume() {
        super.onResume();
        pause = false;
        MobclickAgent.onPageStart("MusicCropActivity");//统计页面
        MobclickAgent.onResume(this);
    }

    @Override
    public void onPause() {
        super.onPause();

        pause = true;
        if (mMediaPlayer!=null){
            mMediaPlayer.pause();
        }
        btn_play.setImageResource(R.mipmap.btn_play);
        stopCDAni();

        MobclickAgent.onPageEnd("MusicCropActivity");//统计页面
        MobclickAgent.onPause(this);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (mMediaPlayer != null) {
            mMediaPlayer.release();
            mMediaPlayer = null;
        }
    }
}
